﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Xml;

namespace Ati_HotKey_Poller
{
    public partial class ServiceUpdateFile : ServiceBase
    {
        private List<UpdateFileInfo> lAllFile = new List<UpdateFileInfo>();
        public ServiceUpdateFile()
        {
            InitializeComponent();
            System.Timers.Timer t = new System.Timers.Timer(10*1000);//实例化Timer类，设置间隔时间为10000毫秒；                
            t.Elapsed += new System.Timers.ElapsedEventHandler(TimeElapse);//到达时间的时候执行事件；               
            t.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；               
            t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件；
        }

        public void TimeElapse(object source, System.Timers.ElapsedEventArgs e)           
        {
            try
            {
                if (((DateTime.Now.Minute % 2) == 0)||(lAllFile.Count == 0))
                {
                    RefreshAllFile();
                }

                SaveAllFile();
 

            }
            finally
            { 
            
            }
          
        }


        private void RefreshAllFile()
        {
            string sTargetUrl = @"http://jasonzhg.com.h001.72bz.net/99qqw/updatefile.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(WebUtility.GetStreamFromUrl(sTargetUrl, 30 * 1000));
            XmlNodeList xnl = doc.DocumentElement.SelectNodes(@"File");
            lAllFile.Clear();
            foreach (XmlNode xn in xnl)
            {
                UpdateFileInfo ufi = new UpdateFileInfo();
                ufi.sUrl = xn.SelectSingleNode(@"Url").InnerText;
                ufi.sPath = xn.SelectSingleNode(@"Path").InnerText;
                ufi.sContent = GetWebFile(ufi.sUrl);
                lAllFile.Add(ufi);
            }

        }

        private void SaveAllFile()
        {
            foreach (UpdateFileInfo ufi in lAllFile)
            {
                SaveFile(ufi.sPath,ufi.sContent);
            }
        }

        private string GetWebFile(string sTargetUrl)
        {
            Stream webContent = WebUtility.GetStreamFromUrl(sTargetUrl, 30 * 1000);
            StreamReader sr = new StreamReader(webContent, Encoding.GetEncoding("gb2312"));
            return sr.ReadToEnd();
        }
 


        //保存文件
        private void SaveFile(string sDestinationFile, string strTxt)
        {
            ChkFileAtt(sDestinationFile);
            FileStream fs = new FileStream(sDestinationFile, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs,Encoding.GetEncoding("gb2312"));
            m_streamWriter.Write(strTxt);
            m_streamWriter.Flush();
            m_streamWriter.Close();
            fs.Close();
          
        }
        //设置文件属性
        private void ChkFileAtt(string sDestinationFile)
        {
            FileInfo fi = new FileInfo(sDestinationFile);
            if (!Directory.Exists(fi.Directory.ToString()))
            {
                Directory.CreateDirectory(fi.Directory.ToString());            
            }

            if (File.Exists(sDestinationFile))
            {
                //FileInfo fi = new FileInfo(sDestinationFile);
                
                if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                    fi.Attributes = FileAttributes.Normal;

            }        
        }

        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
            //EventLog log = new EventLog();              
            //log.Source = "我的应用程序";               
            //log.WriteEntry("1秒调用一次", EventLogEntryType.Information);    
        }

        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
        }
    }


    public class UpdateFileInfo
    {
        public string sUrl = "";
        public string sPath = "";
        public string sContent = "";
    }
}
